package com.etc.myblog.ser;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.myblog.biz.ArticleBiz;
import com.etc.myblog.biz.ScolumnBiz;
import com.etc.myblog.entity.Article;
import com.etc.myblog.entity.ColumnArtCount;
import com.etc.myblog.entity.Scolumn;
import com.etc.myblog.entity.User;
import com.etc.myblog.entity.UserArtCount;
import com.etc.myblog.util.PageUtil;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class ScolumnSer extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//获取服务器中项目根目录
		String savePath =     
				  request.getServletContext().getRealPath("/columnImg");
		java.io.File uploadDir = new java.io.File(savePath);
		//如果此目录不存在，新建该目录
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
		
		ScolumnBiz biz = new ScolumnBiz();
		ArticleBiz artBiz = new ArticleBiz();
		
		if(request.getParameter("tag")!=null) {
			String tag = request.getParameter("tag");
			if(tag.equals("scolumnAd")){
				if(request.getParameter("columnId")!=null && request.getParameter("columnId") != ""){
					int columnId = Integer.parseInt(request.getParameter("columnId"));
					Scolumn column = biz.findById(columnId);
					request.setAttribute("column", column);
					request.getRequestDispatcher("user/userColumnAd.jsp").forward(request, response);
					return;
					
				}
				List<Scolumn> scolumn = new ArrayList<Scolumn>();
				User userLogin = new User();
				userLogin = (User) request.getSession().getAttribute("user");
				scolumn = biz.findAllByUserId(userLogin.getUserId());
				request.setAttribute("column", scolumn);
				request.getRequestDispatcher("user/columnList.jsp").forward(request, response);
				return;
				
			} else if(tag.equals("update")){
				
				Scolumn scolumn = new Scolumn();	
				//新建一个SmartUpload,因form使用了enctype="multipart/form-data"
				//所以值变成二进制数据,request无法获取,故需要用此类获取值
				SmartUpload su = new SmartUpload();
				// 上传初始化
				su.initialize(this.getServletConfig(), request, response);//初始化su
				// 设定上传限制
				// 1.限制每个上传文件的最大长度。
				 su.setMaxFileSize(1024*1024*1024);		//限制为1M
				// 2.限制总上传数据的长度。
				 su.setTotalMaxFileSize(1024*1024*1024*2);	//限制为2M
				// 3.设定允许上传的文件（通过扩展名限制）,仅允许doc,txt文件。
				 su.setAllowedFilesList("jpg,jpeg,png,gif");
				// 4.设定禁止上传的文件（通过扩展名限制）,禁止上传带有exe,bat,jsp,htm,html扩展名的文件和没有
				//扩展名的文件。
				try {
					su.setDeniedFilesList("exe,bat,jsp,htm,html");
				} catch (SQLException e1) {
					System.out.println(e1.getMessage());
					return;
				}
				try {	// 上传文件,采用UTF-8编码
					su.upload("utf-8");	
				} catch (SmartUploadException e) {
					System.out.println(e.getMessage());
					return;
				}
				//获取刚上传的文件
				File file = su.getFiles().getFile(0);
				//获取文件名
				String imgName = file.getFileName();
				if (!su.getFiles().getFile(0).isMissing()) {	//判断是否存在文件，如果文件存在
					int count = 0;
					try {
						count = su.save("/columnImg");
						String serimgPath = "/columnImg/";
						String imgPath = serimgPath + imgName;
						// 设置用户头像的图片路径
						scolumn.setColumnImgUrl(imgPath);
						}
					 catch (SmartUploadException e) {
						System.out.println(e.getMessage());
					}
				}
				
				String columnName = su.getRequest().getParameter("columnName");
				String desc = su.getRequest().getParameter("desc");
				scolumn.setColumnDesc(desc);
				scolumn.setColumnName(columnName);
				scolumn.setColumnStatus("未审核");
				User userLogin = new User();
				userLogin = (User) request.getSession().getAttribute("user");
				scolumn.setUser(userLogin);
				if (su.getRequest().getParameter("columnId") != null && !su.getRequest().getParameter("columnId").equals("")) {
					System.out.println("_");
					int columnId  = Integer.parseInt(su.getRequest().getParameter("columnId"));
					scolumn.setColumnId(columnId);
					if( imgName.equals("")) {
						biz.updateNopic(scolumn);
					} else {
						biz.update(scolumn);
					}
					response.sendRedirect("ScolumnSer?tag=scolumnAd");
					return;
				}
				biz.add(scolumn);
				response.sendRedirect("ScolumnSer?tag=scolumnAd");
				return;
				
			}
			
			int columnId = Integer.parseInt(request.getParameter("columnid"));
			List<Article> listArt = new ArrayList<>();
			Scolumn scolumn = new Scolumn();
			scolumn = biz.findById(columnId);
			listArt = artBiz.findByColumn(columnId);
			ColumnArtCount caCount = new ColumnArtCount();
			//设置专栏的点击量和文章数
			caCount.setScolumn(scolumn);
			caCount.setArticleCount(biz.articleCount(columnId));
			caCount.setArticleView(biz.articleView(columnId));
			
			request.setAttribute("caCount", caCount);
			request.setAttribute("listArt", listArt);
			request.getRequestDispatcher("user/columnDetail.jsp").forward(request,response);
			return;
			
		}
		List<Scolumn> allList = biz.find();
		Scolumn randscol = new Scolumn();
		randscol = biz.findRandColumn();
		ColumnArtCount caCountR = new ColumnArtCount();
		
		//设置专栏的点击量和文章数
		caCountR.setScolumn(randscol);
		caCountR.setArticleCount(biz.articleCount(randscol.getColumnId()));
		caCountR.setArticleView(biz.articleView(randscol.getColumnId()));
		//设置专栏的点击量和文章数
		
		List<ColumnArtCount> scolartCount = new ArrayList<>();

		for(int i=0; i<allList.size(); i++) {
			ColumnArtCount count = new ColumnArtCount();
			count.setScolumn(allList.get(i));
			count.setArticleCount(biz.articleCount(allList.get(i).getColumnId()));
			count.setArticleView(biz.articleView(allList.get(i).getColumnId()));
			scolartCount.add(count);
		}
		
		request.setAttribute("rand", caCountR);
		request.setAttribute("pScUtil", scolartCount);
		request.getRequestDispatcher("user/webColumn.jsp").forward(request,response);
	}

}
